package controllers;

import static play.modules.pdf.PDF.renderPDF;

import java.text.SimpleDateFormat;
import java.util.Date;

import models.AppUser;
import models.Client;
import models.Profile;
import models.ProfileLanguages;
import models.UserRole;

import org.allcolor.yahp.converter.IHtmlToPdfTransformer;

import controllers.tools.Tools;

import play.Logger;
import play.modules.pdf.PDF.Options;
import play.mvc.Before;
import play.mvc.Controller;

public class PDFRenderer extends Controller {

	private static models.Collaborator _CURRENT_COLLABORATOR;

	private static models.AppUser _CONNECTED_USER;

	@Before
	static void setConnectedUser() {
		if (Authentication.isConnected()) {
			// Get the connected user using its login (provided by the security
			// module)
			_CONNECTED_USER = AppUser.find("login = ?",
					Authentication.connected()).first();
		} else {
			error("Unauthorized access !");
		}
	}

	/**
	 * 
	 * @param username
	 */

	private static void loadProfile(String username) {

		if (Authentication.isConnected() == false) {
			error("Unauthorized access !");
		}

		// Get the user associated to the requested profile
		AppUser requestedCollaboratorProfileUser = AppUser.find("login = ?",
				username).first();
		if (requestedCollaboratorProfileUser == null) {
			error("Invalid Request !");
		}

		// 1. Connected user : Collaborator Case
		if (Authentication.check(UserRole.COLLABORATOR.name())) {

			// Get the collaborator associated to the connected user and
			// give it to the view in order to display collaborator data
			_CURRENT_COLLABORATOR = models.Collaborator.find("user = ?",
					requestedCollaboratorProfileUser).first();

			// If the user doesn't have a registered profile : create a blank
			// one
			if (_CURRENT_COLLABORATOR == null) {

				// Create entities
				_CURRENT_COLLABORATOR = new models.Collaborator();
				_CURRENT_COLLABORATOR.setUser(requestedCollaboratorProfileUser);

				Profile profile = new Profile();
				profile.save();

				_CURRENT_COLLABORATOR.setValidProfile(profile);
				_CURRENT_COLLABORATOR.setTmpProfile(profile);
				_CURRENT_COLLABORATOR.save();
			}

			// If the profile is requested by another collaborator : error !
			if (_CURRENT_COLLABORATOR.getUser() != _CONNECTED_USER) {
				error("Unauthorized access !");
			}
		}
		// 2. Connected user : RTU Case
		else if (Authentication.check(UserRole.RTU.name())) {
			// Get the collaborator associated to the connected user and
			// give it to the view in order to display collaborator data
			_CURRENT_COLLABORATOR = models.Collaborator.find("user = ?",
					requestedCollaboratorProfileUser).first();
		}
		// 3. Connected user : Other cases
		else {
			error("Unauthorized access !");
		}

		// Logging
		Logger.debug("[PDFRenderer] Collaborator object [ID : %s] : Loaded.",
				_CURRENT_COLLABORATOR.getCollaboratorID());
	}

	/**
	 * Load extra data before view rendering
	 */

	private static void loadModelElements() {
		// Put an instance of our tools class into the view
		renderArgs.put("tools", new Tools());
		// Put all collaborator's languages into the view
		renderArgs.put(
				"languages",
				ProfileLanguages.find("profile = ?",
						_CURRENT_COLLABORATOR.getValidProfile()).fetch());
		// Put the connected user into the view
		renderArgs.put("user", _CONNECTED_USER);
		// Put the collaborator object to the view
		renderArgs.put("collab", _CURRENT_COLLABORATOR);

		// Logging
		Logger.debug("[PDFRenderer] Model elements : Loaded.",
				_CURRENT_COLLABORATOR.getCollaboratorID());
	}

	// ///////////////////////////////////////////
	// //// RENDERING METHODS
	// ///////////////////////////////////////////

	/**
	 * Render a PDF page which represents the profile page
	 */

	public static void generateProfilePDF(String username) {

		// Load the collaborator profile
		loadProfile(username);
		// Load extra data before view rendering
		loadModelElements();

		Profile profile = _CURRENT_COLLABORATOR.getValidProfile();
		if (profile == null) {
			return;
		}
		// Title and content
		String title = profile.getFirstname() + " " + profile.getName()
				+ "profile";

		// Options
		Options options = new Options();
		options.filename = _CURRENT_COLLABORATOR.getUser().getLogin()
				+ "_profile.pdf";
		// The A4 format (the format proposed by the standard implementation was
		// not very convenient)
		options.pageSize = new IHtmlToPdfTransformer.PageSize(21, 29.7, 1.2,
				1.1, 1.8, 1.2);

		// Footer
		SimpleDateFormat formater = new SimpleDateFormat("dd-MM-yy");
		options.FOOTER = "<span style='float: right;font-size: 8pt;'>Page <pagenumber>/<pagecount></span>"
				+ "<center style='font-size: 8pt; font-style:italic;'> <span style='font-weight:bold;'> Eurogiciel Ingénierie </span> <br/> Domaine du Millénium - 6 avenue Henri Le Chatelier - 33700 Mérignac - <span style = 'text-decoration:underline;'> www.eurogiciel.fr </span> <br/> Téléphone : 05 57 92 38 38 - Télécopie : 05 57 92 38 39 <br/>  </center>"
				+ "<span style='font-size: 8pt; float:left;'>Fiche Profil-"
				+ formater.format(new Date()) + "</span>";

		// Logging
		Logger.debug(
				"[PDFRenderer] Rendering PDF collaborator (%s) profile page...",
				username);

		// Render PDF to the client
		renderPDF(options, title);
	}

}
